package com.mrx.xfriendship.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mrx.commons.annotations.XLog;
import com.mrx.commons.util.asserts.Asserts;
import com.mrx.xfriendship.converter.TagConverter;
import com.mrx.xfriendship.dao.TagMapper;
import com.mrx.xfriendship.model.dto.PageDTO;
import com.mrx.xfriendship.model.dto.TagDTO;
import com.mrx.xfriendship.model.po.TagPO;
import com.mrx.xfriendship.model.vo.TagManagerPageVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Mr.X
 * @since 2023-01-14 10:07
 */
@XLog
@Service
@DubboService
public class TagServiceImpl implements ITagService {

    @Resource
    private TagMapper tagMapper;

    @Resource
    private TagConverter tagConverter;

    @Override
    public List<TagDTO> listTags() {
        return tagConverter.toDTO(tagMapper.selectAll());
    }

    @Override
    public PageDTO<TagDTO> listTags(TagManagerPageVO vo) {
        try (Page<?> page = PageHelper.startPage(vo.getPage(), vo.getSize())) {
            return PageDTO.newPage(vo, tagConverter.toDTO(tagMapper.selectPage(vo)), page.getTotal());
        }
    }

    @Override
    public TagDTO findTagById(Integer id) {
        return tagConverter.toDTO(tagMapper.selectByPrimaryKey(id));
    }

    @Override
    public void updateTag(TagDTO dto) {
        Asserts.EDIT_FAILED_NAME_NOT_EMPTY.checkTrue(StringUtils.hasText(dto.getName()));
        tagMapper.updateByPrimaryKeySelective(tagConverter.toPO(dto));
    }

    @Override
    public void delete(Integer id) {
        TagPO tagPO = tagMapper.selectByPrimaryKey(id);
        Asserts.CAN_NOT_DELETE_REFERENCED_TAG.checkTrue(tagPO.getPostCount().equals(0));
        tagMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void addTag(TagDTO dto) {
        Asserts.EDIT_FAILED_NAME_NOT_EMPTY.checkTrue(StringUtils.hasText(dto.getName()));
        Asserts.TAG_ALREADY_EXISTS.checkFalse(tagMapper.checkNameExists(dto.getName()));
        TagPO po = new TagPO();
        po.setName(dto.getName());
        tagMapper.insertSelective(po);
    }

}
